package logic

import (
	"context"
	"errors"
	"practice-one/models/cache"
	"practice-one/models/mysql"
	"practice-one/pkg"

	"practice-one/userrpc/internal/svc"
	"practice-one/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *userrpc.UserLoginRequest) (*userrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	if in.LoginType == 1 || in.LoginType == 2 {
		if err := user.FindUserByTel(mysql.DB, in.Tel); err != nil {
			return nil, err
		}
		if user.ID == 0 {
			return nil, errors.New("该手机号未注册用户")
		}
		if in.LoginType == 1 {
			if pkg.Md5(in.Password) != user.Password {
				return nil, errors.New("密码不正确,请重试")
			}
		}
		if in.LoginType == 2 {
			result, _ := cache.Rdb.Get(l.ctx, "smsCode_"+in.Tel).Result()
			if result != in.SmsCode {
				return nil, errors.New("短信验证码不正确,请重试")
			}
		}
	} else {
		return nil, errors.New("请选择正确的登录方式")
	}

	return &userrpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
